<template>
  <el-row :gutter="20" style="margin-bottom: 10px;">
      <el-col :span="6" >
          <el-button size="large"  
              @click="dialogFormVisible = true" >新增用户</el-button>
      </el-col>
      <el-dialog v-model="dialogFormVisible" title="新增用户" width="500">
        <el-form :model="form">
          <el-form-item label="用户名称" >
            <el-input v-model="form.username" autocomplete="off" />
          </el-form-item>
          
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addUser">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
  </el-row>
  <el-row style="margin:0 20px;">
    <el-table :data="users" stripe style="width: 100%" highlight-current-row >
      <el-table-column prop="userId" label="用户编号" width="180" />
      <el-table-column prop="username" label="用户名称" width="180"/>
      <el-table-column prop="userRole" label="用户角色" width="180" />
      <el-table-column prop="userState" label="启用" width="180" :formatter="boolFormat"/>
      <el-table-column label="操作">
        <template #default="scope">
        <el-button
          size="small"
          type="danger"
          @click="swithState(scope.$index, scope.row)"
          >
          <el-text v-if="scope.row.userState" style="color: #fff;">停用</el-text>
          <el-text v-else style="color: #fff;">启用</el-text>
          </el-button>
        </template>

      </el-table-column>
    </el-table>
  </el-row>
</template>

<script  setup>

import { getCurrentInstance,ref,onBeforeMount,reactive } from "vue"

let dialogFormVisible = ref(false)
const users = ref([])
import { useStore } from '@/stores'

const { proxy } = getCurrentInstance()

function boolFormat(row, column, cellValue, index){
    return cellValue?'是':'否'
}
const store = useStore()
onBeforeMount(()=>{
  getUsers()
})

async function getUsers(){
  let { data: res} = await proxy.$http({
    method:'get',
        headers: {
      'Authorization': store.token	//	可以是授权凭证用的参数值
      },
    url:'/api/admin/user'
	})
  console.log(res.data)
  users.value=res.data
}

const handleEdit = (index, row) => {
  console.log(index, row)
}
const swithState =async (index, row) => {
  console.log(index, row)
  let { data: res} = await proxy.$http({
    method:'put',
        headers: {
      'Authorization': store.token	//	可以是授权凭证用的参数值
      },
    url:`/api/admin/user/${row.userId}`
	})
  row.userState=!row.userState
  console.log(res)
}

const form = reactive({
  username: '',
})

async function addUser(){
  let { data: res} = await proxy.$http({
    method:'post',
    headers: {
      'Authorization': store.token	//	可以是授权凭证用的参数值
    },
    data:form,
    url:'/api/admin/user'
	})
  dialogFormVisible.value = false
  getUsers()
}

</script>
